﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Security;
using Medianamik.Core;
using Medianamik.Core.Profile;
using Medianamik.Core.Security;
using Medianamik.Service.ActiveDirectory.DTO;

namespace Medianamik.Service.ActiveDirectory.Repository
{
    public class MembershipRepository : IMembershipRepository
    {
        public MedianamikUser LoadAndCreateUserWithDomainUser(IDomainUser domainUser)
        {
            var loadedUser = Membership.GetUser(domainUser.UserName);

            if (loadedUser == null)
            {
                var user = Membership.CreateUser(domainUser.UserName, 
                    Membership.GeneratePassword(10, 3), domainUser.Email);
                user.IsApproved = true;
                Membership.UpdateUser(user);
                var profile = NodeManager.NewNode<ProfileNode>(CultureInfo.InvariantCulture, 
                    MedianamikModules.SecurityManagement);
                profile.SubscriptionDate = DateTime.Now;
                profile.UserId = (Guid)user.ProviderUserKey;
                profile.FullName = domainUser.FullName;
                profile.DefaultInstance.Properties["UICultureName"]
                    .SetValue(MedianamikContext.Current.CurrentUICulture.Name);
                NodeManager.SaveNode(profile);

                return (MedianamikUser)user;
            }

            return (MedianamikUser)loadedUser;
        }

        public void SetUserPermissions(string userName, IEnumerable<string> groups)
        {
            Core.Security.Roles.RemoveUserFromGroups(userName, 
                SecurityManager.AllGroups.Select(g => g.GroupName).ToArray());
            Core.Security.Roles.AddUserToGroups(userName, groups.ToArray());
        }

        public IEnumerable<string> GetAllGroupNames()
        {
            return SecurityManager.AllGroups.Select(group => group.Name);
        }
    }

    public interface IMembershipRepository
    {
        MedianamikUser LoadAndCreateUserWithDomainUser(IDomainUser domainUser);
        void SetUserPermissions(string userName, IEnumerable<string> groups);
        IEnumerable<string> GetAllGroupNames();
    }
}
